import React, { Fragment } from 'react'
import { ScrollView, StyleSheet, Text } from 'react-native'
import { connect } from 'react-redux'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import { UPDATE_USERINFO_ACTION } from '@store/actions/userinfo'
import PromptModal from 'src/components/modal/PromptModal'
import NextButton from 'src/components/button/NextButton'
import CustomBoxShadow from 'src/components/boxshadow/CustomBoxShadow'
import CustomInputLabel from 'src/components/button/CustomInputLabel'
import {
  addJobHunting,
  editJobHunting,
  delJobHunting
} from 'src/utils/RequestAPI'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { isString } from 'src/utils/JSTypeUtil'
import CustomButton from 'src/components/button/CustomButton'
// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  }
})

@connect(
  ({ userinfo, CMineCenterStore }) => ({
    userId: userinfo.C.userId,
    userName: userinfo.C.userName,
    jobHuntingModelsLength: CMineCenterStore.jobHuntingModels && CMineCenterStore.jobHuntingModels.length,
    archiveId: CMineCenterStore.archiveInfo.archiveId
  }),
  mapDispatchToProps
)
class CUserJobIntentionEdit extends BasePage {
  constructor (props) {
    super(props)
    const {
      navigation: {
        state: {
          params: { jobIntention }
        }
      }
    } = this.props
    this.state = {
      header: {},
      saveVisible: false,
      deleteVisible: false,
      saveEnable: false,
      id: jobIntention.id,
      jobPlace: jobIntention.jobPlace || '',
      workNature: jobIntention.workNature || [],
      workPlace: jobIntention.workPlace || [],
      workCategory: jobIntention.workCategory || []
    }
  }

  static getDerivedStateFromProps (props, state) {
    console.log('getDerivedStateFromProps', state)
    return CUserJobIntentionEdit.saveButtonEnable(state)
  }

  // componentDidMount () {
  //   const state = CUserJobIntentionEdit.saveButtonEnable(this.state)
  //   state && this.setState(state)
  // }
  static saveButtonEnable (state) {
    const { jobPlace, workNature, workPlace, workCategory } = state
    const saveEnable = !!(
      jobPlace &&
      workNature &&
      workNature.length &&
      workPlace &&
      workPlace.length &&
      workCategory &&
      workCategory.length
    )
    if (state.saveEnable !== saveEnable) {
      console.log('saveEnable', saveEnable)
      return {
        saveEnable
      }
    }
    return null
  }

  childRender () {
    const {
      saveVisible,
      deleteVisible,
      id,
      workNature,
      workCategory,
      workPlace,
      jobPlace
    } = this.state
    const { jobHuntingModelsLength } = this.props
    const workNatureValue = (workNature && workNature[0]) || ''
    return (
      <Fragment>
        <ScrollView style={styles.container} contentContainerStyle={styles.scrollContentView}>
          <Text style={styles.editJobIntentionTitle}>编辑求职意向</Text>
          <Text style={styles.editJObIntentionTip}>
            *求职意向的不同，推荐的职位也会不同
          </Text>
          <CustomBoxShadow style={styles.editJobContent}>
            <CustomInputLabel
              title="工作性质"
              value={workNatureValue}
              placeHolder="请选择"
              onPress={this._workNatureClick}
            />
            <CustomInputLabel
              title="工作区域"
              value={
                jobPlace && workPlace && workPlace.length
                  ? `${jobPlace}·${workPlace.join(' ')}`
                  : ''
              }
              placeHolder="请选择"
              onPress={this._workPlaceClick}
            />
            <CustomInputLabel
              title="期望职位"
              value={`${workCategory.join(' ')}`}
              placeHolder="请选择"
              last={true}
              onPress={this._workCategoryClick}
            />
          </CustomBoxShadow>
          {id && jobHuntingModelsLength > 1 && (
            <NextButton
              style={styles.nextButton}
              title="删除本条"
              enable={true}
              onPress={this.onDeleteClick}
            />
          )}
        </ScrollView>
        <PromptModal
          visible={deleteVisible}
          onCancel={this.onDeleteCancel}
          onConfirm={this.onDeleteConfirm}
          onModalHide={this.onDeleteModalHide}
          config={{
            titleText: '温馨提示',
            contentText: '确定删除这条求职意向吗？'
          }}
        />
        <PromptModal
          visible={saveVisible}
          onCancel={this.onSaveCancel}
          onConfirm={this.onSaveConfirm}
          onModalHide={this.onSaveModalHide}
          config={{
            titleText: '温馨提示',
            contentText: '内容尚未保存，确定放弃吗？'
          }}
        />
      </Fragment>
    )
  }

  renderNavigationBarChild = () => {
    const { saveEnable } = this.state
    return (
      <CustomButton style={styles.saveBtn} onPress={this._saveButtonClick}>
        <Text style={[styles.saveText, saveEnable && styles.saveTextEnable]}>
          保存
        </Text>
      </CustomButton>
    )
  }

  _workNatureClick = () => {
    const callback = workNature => {
      if (
        workNature &&
        workNature[0] &&
        this.state.workNature &&
        this.state.workNature[0] &&
        workNature[0] !== this.state.workNature[0]
      ) {
        this.setState({
          workCategory: []
        })
      }
      this.setState({
        workNature
      })
    }
    const { workNature, id } = this.state
    this.props.navigation.navigate('CUserJobNature', {
      workNature,
      id,
      callback
    })
  }

  _workPlaceClick = () => {
    const callback = (jobPlace, workPlace) => {
      this.setState({
        jobPlace,
        workPlace
      })
    }
    const { jobPlace, workPlace } = this.state
    this.props.navigation.navigate('CUserJobArea', {
      jobPlace,
      workPlace,
      callback
    })
  }

  _workCategoryClick = () => {
    const { workNature, workCategory } = this.state
    const workNatureValue = (workNature && workNature[0]) || ''
    if (!workNatureValue) {
      CommonToast('请先选择工作性质')
      return
    }
    const callback = workCategory => {
      this.setState({
        workCategory
      })
    }
    this.props.navigation.navigate('CUserJobExpected', {
      workCategory,
      workNature,
      callback
    })
  }

  onDeleteClick = () => {
    this.toggleTipVisible('deleteVisible', true)
  }

  onDeleteCancel = () => {
    this.toggleTipVisible('deleteVisible', false)
  }

  onDeleteConfirm = () => {
    this.toggleTipVisible('deleteVisible', false)
  }

  onDeleteModalHide = res => {
    if (res) {
      const { id } = this.state
      const {
        navigation: {
          state: {
            params: { callback }
          }
        },
        userId
      } = this.props

      /* 删除 */
      const params = {
        id,
        userId
      }
      ShowLoading()
      delJobHunting({ params }).then(res => {
        callback && callback()
        this.props.navigation.goBack()
      }).finally(() => {
        DismissLoading()
      })
    }
  }

  _saveButtonClick = () => {
    const {
      saveEnable,
      jobPlace,
      workNature,
      workPlace,
      workCategory
    } = this.state
    if (!saveEnable) {
      return
    }
    const {
      navigation: {
        state: {
          params: { jobIntention, callback }
        }
      },
      userId,
      userName,
      archiveId
    } = this.props
    const { id } = jobIntention
    if (id) {
      /* 修改 */
      const comprehensive = {
        workNature,
        workPlace,
        workCategory
      }
      const params = {
        comprehensive: JSON.stringify(comprehensive),
        jobPlace,
        id,
        userId,
        userName
      }
      ShowLoading()
      editJobHunting({ params }).then(res => {
        callback &&
        callback({
          ...res.data,
          ...comprehensive
        })
        this.props.navigation.goBack()
      }).finally(() => {
        DismissLoading()
      })
    } else {
      const comprehensive = {
        workNature,
        workPlace,
        workCategory
      }
      const params = {
        comprehensive: JSON.stringify(comprehensive),
        jobPlace,
        userId,
        userName,
        archiveId
      }
      ShowLoading()
      addJobHunting({ params }).then(res => {
        callback &&
        callback({
          ...res.data,
          ...comprehensive
        })
        this.props.navigation.goBack()
      }).finally(() => {
        DismissLoading()
      })
    }
  }

  onSaveConfirm = () => {
    this.onSaveCancel()
  }

  onSaveCancel = () => {
    this.toggleTipVisible('saveVisible', false)
  }

  onSaveModalHide = ensure => {
    ensure && this.props.navigation.goBack()
  }

  goBack = () => {
    const {
      navigation: {
        state: {
          params: { jobIntention }
        }
      }
    } = this.props
    const { saveEnable } = this.state
    if (saveEnable && !this.comprehensiveEqual(jobIntention, this.state)) {
      this.toggleTipVisible('saveVisible', true)
    } else {
      this.props.navigation.goBack()
    }
  }

  toggleTipVisible = (visible, value) => {
    this.setState({
      [visible]: value
    })
  }

  comprehensiveEqual = (comprehensive1, comprehensive2) => {
    const keys = ['workCategory', 'workNature', 'workPlace', 'jobPlace']
    return keys.every(e => {
      const value1 = comprehensive1[e]
      const value2 = comprehensive2[e]
      return isString(value1)
        ? value1 === value2
        : JSON.stringify(value1) === JSON.stringify(value2)
    })
  }
}

export default CUserJobIntentionEdit

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  scrollContentView: {
    paddingBottom: ScaleS(90)
  },
  editJobIntentionTitle: {
    color: '#444444',
    fontSize: ScaleT(27),
    fontWeight: '500',
    marginTop: ScaleS(30),
    marginLeft: ScaleS(20)
  },
  editJObIntentionTip: {
    color: '#FFC200',
    fontSize: ScaleT(12),
    fontWeight: '400',
    marginTop: ScaleS(20),
    marginLeft: ScaleS(20)
  },
  editJobContent: {
    width: ScaleS(335),
    height: ScaleS(230),
    marginLeft: ScaleS(20),
    shadowRadius: ScaleS(40),
    shadowOpacity: 0.25,
    shadowColor: '#9C9C9C',
    borderRadius: ScaleS(10),
    paddingHorizontal: ScaleS(16),
    backgroundColor: '#FFFFFF',
    marginTop: ScaleS(40),
    shadowOffset: {
      width: 0,
      height: ScaleS(7)
    }
  },
  contentItem: {
    height: ScaleS(76),
    alignItems: 'center',
    flexDirection: 'row'
  },
  contentItemLabel: {
    color: '#444444',
    fontSize: ScaleT(16),
    fontWeight: '600',
    flex: 1
  },
  contentItemRightLabel: {
    color: '#444444',
    fontSize: ScaleT(16),
    fontWeight: '400',
    marginRight: ScaleS(16)
  },
  contentItemImg: {
    width: ScaleS(6),
    height: ScaleS(12)
  },
  contentItemLine: {
    backgroundColor: '#EFEFEF',
    height: ScaleS(1)
  },
  nextButton: {
    position: 'absolute',
    bottom: ScaleS(20),
    left: ScaleS(32)
  },
  saveBtn: {
    alignSelf: 'flex-end',
    marginRight: ScaleS(20)
  },
  saveText: {
    color: '#bbbbbb',
    fontSize: ScaleT(16),
    fontWeight: '400'
  },
  saveTextEnable: {
    color: '#000000'
  }
})
